angular.module('U9ImHd.services')

.factory('DevicePort', ['$q', '$rootScope', 'SerialPort', 'imanUsbPort', 'imanDialog',
    function ($q, $rootScope, SerialPort, imanUsbPort, imanDialog) {
        var _notify = 0,
            _parseFn = null,
            _errHandler = true;

        return {
            init: init,
            open: openPort,
            close: closePort
        };

        function init () {
            document.addEventListener('serialport.DataReceived', function (e) {
                if (_notify !== 1) {
                    return;
                }
                onProcess(_parseFn ? _parseFn(e.serialPortData) : e.serialPortData);
            }, false);
            $rootScope.$on('imanUsbPort.input', function (e, data) {
                if (_notify !== 2) {
                    return;
                }
                onProcess(data);
            });
        }

        function onProcess (data) {
            if (!data) {
                if (_errHandler) {
                    imanDialog.toastBottom("异常扫描");
                }
                return;
            }
            $rootScope.$broadcast('devicePort.DataReceived', data);
        }

        function openPort (opts) {
            var defer = $q.defer();
            
            if (opts.hasOwnProperty('errHandler')) {
                _errHandler = opts.errHandler;
            }
            if (_notify) {
                closePort();
            }
            if (opts) {
                SerialPort.open(opts).then(function () {
                    _notify = 1;
                    if (angular.isFunction(opts.parseFn)) {
                        _parseFn = opts.parseFn;
                    } else {
                        _parseFn = !!opts.parseFn ? defaultParseFn : null;
                    }
                    defer.resolve();
                }, function () {
                    imanUsbPort.start();
                    _notify = 2;
                    defer.resolve();
                });
            } else {
                imanUsbPort.start();
                _notify = 2;
                defer.resolve();
            }

            return defer.promise;
        }

        function closePort () {
            if (!_notify) {
                return;
            }
            _notify = 0;
            _errHandler = true;
            SerialPort.close();
            _parseFn = null;
            imanUsbPort.stop();
        }

        function defaultParseFn (data) {
            var parse = '00000000',
                checkLen = 4,
                splitStrs = data.split(parse),
                temp = splitStrs[splitStrs.length - 1];
            temp = temp.substr(0, data.length - checkLen);
            var result = {}, r = '';
            for (var i = 0; i < temp.length; i += 2) {
                r += String.fromCharCode(parseInt(temp.substr(i, 2), 16));
            }
            var reList = r.split('&');
            for (var j = 0; j < reList.length; j++) {
                var littleName = reList[j].split('=');
                if (reList.length < 2) {
                    continue;
                }
                result[littleName[0]] = littleName[1];
            }
            return result.Barcode;
        }
    }
]);